let utils = require('../../../utils/utils.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        connectingDeviceId: '',
        services_UUID: '',
        characteristic_UUID: '',
        connected: false,
        used_space: '',
        total_space: '',
        volume: 0,
        version: '',
        sceneId: 0, //场景id
        scene: '', //场景
        sceneArray: [], //磁盘目录
        isOpenSpace: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            connectingDeviceId: options.connectingDeviceId
        });
        //连接蓝牙
        this.connectBLE();
    },

    /**
     * 连接设备
     */
    connectBLE() {
        let deviceId = this.data.connectingDeviceId;
        if (deviceId) {
            // 断开与低功耗蓝牙设备的连接 然后再连接新的设备
            this.closeConnection(deviceId);
            // 连接低功耗蓝牙设备
            this.connetBlueDeviceId(deviceId);
            // 设置MTU，否则只能接收512字节
            utils.exchange_mtu(deviceId);
        }
    },

    // 断开与低功耗蓝牙设备的连接
    closeConnection() {
        if (!this.data.connected) {
            return;
        }
        let connectingDeviceId = this.data.connectingDeviceId;
        if (!connectingDeviceId) {
            return;
        }
        wx.closeBLEConnection({
            deviceId: connectingDeviceId,
            success(res) {
                console.log('断开与低功耗蓝牙设备的连接');
                console.log(res);
            },
            fail() {
                utils.toast('断开连接失败');
            }
        });
    },
    // 连接低功耗蓝牙设备
    connetBlueDeviceId(deviceId) {
        let _this = this;
        utils.loading('连接中...');
        wx.createBLEConnection({
            deviceId: deviceId,
            timeout: 60000,
            success(res) {
                console.log("蓝牙连接返回：", JSON.stringify(res))
                utils.toast('蓝牙连接成功');
                _this.setData({
                    connected: true,
                    connectingDeviceId: deviceId
                });
                _this.getServices(deviceId);
                utils.hide_Loading();
                utils.toast('连接成功');
            },
            fail(res) {
                console.log('连接失败');
                console.log(res);
                _this.setData({
                    connected: false,
                });
                utils.hide_Loading();
            },
        });
    },

    // 获取蓝牙设备所有服务(service) 为了获取service的UUID
    getServices(deviceId) {
        let _this = this;
        wx.getBLEDeviceServices({
            deviceId: deviceId,
            success(res) {
                console.log('获取蓝牙设备service');
                console.log(res);
                let uuid = res.services;
                let len = uuid.length;
                for (let i = 0; i < len; i++) {
                    _this.getCharacteristics(deviceId, res.services[i].uuid);
                }
            },
            fail(res) {
                utils.toast('获取服务失败');
                console.log(res);
            },
        });
    },

    // 获取蓝牙设备某个服务中所有特征值(characteristic) 为了该特征值UUID支持的操作类型
    getCharacteristics(deviceId, servicesId) {
        let _this = this;
        wx.getBLEDeviceCharacteristics({
            deviceId: deviceId,
            serviceId: servicesId,
            success(res) {
                if (res.errCode == 0) {
                    let characteristics = res.characteristics;
                    let len = characteristics.length;
                    for (let k = 0; k < len; k++) {
                        let indicate = characteristics[k].properties.indicate;
                        let notify = characteristics[k].properties.notify;
                        let read = characteristics[k].properties.read;
                        let write = characteristics[k].properties.write;
                        // console.log(characteristics[k].uuid + " 权限： ", "i:" + indicate, "n:" + notify, "r:" + read, "w:" + write);

                        let connectingDeviceId = deviceId;
                        let services_UUID = servicesId;
                        let characteristic_UUID = characteristics[k].uuid;
                        if (write) {
                            //绑定设备
                            let bindParam = '0bind?{"uid":"' + services_UUID + '"}';
                            console.log("bind: ", bindParam)
                            utils.writeToBluetoothValue(connectingDeviceId, services_UUID, characteristic_UUID, bindParam);
                            //设置全局数据
                            _this.setData({
                                services_UUID: servicesId,
                                connectingDeviceId: deviceId,
                                characteristic_UUID: characteristic_UUID,
                            });
                            //0info查询设备信息
                            _this.getBLEInfo(connectingDeviceId, services_UUID, characteristic_UUID)
                        }
                        if (notify) {
                            _this.notifyValueChange(connectingDeviceId, services_UUID, characteristic_UUID);
                        }
                        if (read) {
                            _this.readValue(connectingDeviceId, services_UUID, characteristic_UUID);
                        }
                    } //for
                } //resp
            },
            fail() {
                utils.toast('获取特征值失败');
            }
        });
    },

    // 启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值
    notifyValueChange(deviceId, services_UUID, characteristic_UUID) {
        let _this = this;
        wx.notifyBLECharacteristicValueChange({
            deviceId: deviceId,
            serviceId: services_UUID,
            characteristicId: characteristic_UUID,
            state: true,
            success(res) {
                console.log('启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值: 成功---');
                console.log(res);
                _this.onValueChange();
            },
            fail(res) {
                console.log('启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值: 失败---');
                console.log(res);
            },
        });
    },
    // 读取低功耗蓝牙设备的特征值的二进制数据值
    // 接口读取到的信息需要在 onBLECharacteristicValueChange 方法注册的回调中获取
    readValue(deviceId, services_UUID, characteristic_UUID) {
        wx.readBLECharacteristicValue({
            deviceId: deviceId,
            serviceId: services_UUID,
            characteristicId: characteristic_UUID,
            success(res) {
                console.log('读取低功耗蓝牙设备的特征值的二进制数据值: 成功---');
                console.log(res);
            },
            fail(res) {
                console.log('读取低功耗蓝牙设备的特征值的二进制数据值: 失败---');
                console.log(res);
            }
        });
    },

    // 监听低功耗蓝牙设备的特征值变化
    // 必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。
    onValueChange: function () {
        let _this = this;
        wx.onBLECharacteristicValueChange(function (res) {
            console.log('监听低功耗蓝牙设备的特征值变化');
            console.log("characteristicId：" + res.characteristicId)
            console.log("serviceId:" + res.serviceId)
            console.log("deviceId" + res.deviceId)
            console.log("Length:" + res.value.byteLength)

            // 获取设备返回的数据
            let hex = utils.ab2hex(res.value);
            let ret = utils.hexToStr(hex);
            console.log("蓝牙返回值：", ret)
            if (ret) {
                if (ret.includes("info?")) {
                    _this.bleInfo(ret);
                } else if (ret.includes("sounds?")) {
                    _this.bleSounds(ret);
                }
            }
        });
    },
    //解析蓝牙0info返回值
    bleInfo: function (ret) {
        let _this = this;
        // info?
        let info = ret.substring(5);
        console.log("容量序列化json：", info)
        let jsonInfo = JSON.parse(info);
        _this.setData({
            used_space: Math.round(jsonInfo.used_space / 1024 / 1024),
            total_space: Math.round(jsonInfo.total_space / 1024 / 1024),
            volume: jsonInfo.volume,
            version: jsonInfo.version,
            sceneId: jsonInfo.scene,
        });
        //根据scene查询介绍
        utils.querySceneById(jsonInfo.scene).then(res => {
            let toyScene = res.data.data;
            _this.setData({
                scene: toyScene
            });
        }).catch(error => {
            console.error(error);
        });
    },

    //解析listsounds
    bleSounds: function (ret) {
        let _this = this;
        //stop?{"err":0}sounds?{"err":0,"sounds":["0","1"],"scene":"0"}
        // sounds?{"err": 0, "sounds": ["0"], "scene": "0"}
        let info = ret.substring(7);
        console.log("listsounds序列化json：", info)
        let jsonInfo = JSON.parse(info);
        let sounds = jsonInfo.sounds; //存储目录（可能有很多场景）
        let playscene = jsonInfo.scene; //当前播放的场景
        //场景查询
        let sceneArray = [];
        sounds.forEach(function (senceId) {
            utils.querySceneById(senceId).then(res => {
                let toyScene = res.data.data;
                sceneArray = _this.data.sceneArray;
                sceneArray.push(toyScene);
                _this.setData({
                    sceneArray: sceneArray
                });
                console.log("查询toyScene列表：", JSON.stringify(sceneArray));
            }).catch(error => {
                console.error(error);
            });
        });
    },

    /**
     * 请求蓝牙0info
     */
    getBLEInfo(connectingDeviceId, services_UUID, characteristic_UUID) {
        let infoParam = '0info';
        console.log("0info: ", infoParam)
        utils.writeToBluetoothValue(connectingDeviceId, services_UUID, characteristic_UUID, infoParam);
    },

    //声音开大
    bleTurnUp() {
        let _this = this;
        if (_this.data.volume >= 1) {
            utils.toast("声音已经最大");
            return;
        }
        let volume = Number((_this.data.volume + 0.1).toFixed(1));
        let volumeParam = '0volume?{"volume":"' + volume + '"}';
        console.log("0volume: ", volumeParam)
        utils.writeToBluetoothValue(_this.data.connectingDeviceId, _this.data.services_UUID, _this.data.characteristic_UUID, volumeParam);
        _this.setData({
            volume: volume
        })
    },
    //声音开小
    bleTurnDown() {
        let _this = this;
        if (_this.data.volume <= 0.5) {
            utils.toast("声音已经最小");
            return;
        }
        let volume = Number((_this.data.volume - 0.1).toFixed(1));
        let volumeParam = '0volume?{"volume":' + volume + '}';
        console.log("0volume: ", volumeParam)
        utils.writeToBluetoothValue(_this.data.connectingDeviceId, _this.data.services_UUID, _this.data.characteristic_UUID, volumeParam);
        _this.setData({
            volume: volume
        });
    },

    //设备上的sd卡语言包
    bleManageSpace() {
        let _this = this;
        if (_this.data.isOpenSpace) {
            _this.setData({
                isOpenSpace: false
            });
            return;
        } else {
            _this.setData({
                isOpenSpace: true
            });
        };
        //优化频繁查询，如果sceneArray有数据则不再查询蓝牙
        if (_this.data.sceneArray.length > 0) {
            return;
        }
        let soundsParam = '0listsounds';
        console.log("0listsounds: ", soundsParam)
        utils.writeToBluetoothValue(_this.data.connectingDeviceId, _this.data.services_UUID, _this.data.characteristic_UUID, soundsParam);
    },

    /**
     * 删除磁盘上的场景，在这里id就是删除的目录
     * 1. 删除时候需要调用0stop停止运行
     * 2. stop后需要0start开启
     * @param  e 
     */
    bleDeleteSceneSpace(e) {
        let _this = this;
        let id = e.currentTarget.dataset.id;
        console.log("删除的场景id:", id)
        if (id == undefined) {
            utils.toast("获取场景不能为空～");
            return;
        }
        let stopParam = '0stop';
        console.log("0stop: ", stopParam)
        utils.writeToBluetoothValue(_this.data.connectingDeviceId, _this.data.services_UUID, _this.data.characteristic_UUID, stopParam);

        let removedirParam = '0removedir?{"dir":"/sd/sounds/' + id + '"}';
        console.log("0removedir: ", removedirParam)
        utils.writeToBluetoothValue(_this.data.connectingDeviceId, _this.data.services_UUID, _this.data.characteristic_UUID, removedirParam);

        let startParam = '0start';
        console.log("0start: ", startParam)
        utils.writeToBluetoothValue(_this.data.connectingDeviceId, _this.data.services_UUID, _this.data.characteristic_UUID, startParam);

        _this.deleteSceneArray(id);
    },

    //删除场景列表中的数据
    deleteSceneArray(scenId) {
        let _this = this;
        let sceneArray = _this.data.sceneArray;
        let filteredArray = sceneArray.filter(item => item.id !== scenId);
        _this.setData({
            sceneArray: filteredArray
        });
    },


}); //Page